#!/usr/bin/env python 
# -*- coding:utf-8 -*-

from pymongo import MongoClient
import pymongo
import json

if __name__ == '__main__':
    # 建立数据库连接
    client = MongoClient('localhost', 27017)

    # 标准链接版本
    db = client.get_database('test01')
    coll = db.get_collection('index1')

    # 简化链接版本
    # 连接目标数据库
    # db = client.test01
    # 连接集合
    # coll = db.index3

    # 查询全部1
    # for i in coll.find():
    #     print(i)
    #     print("i.name = {}".format(i.get('name')))
    #     lt = i.get('score')
    #     if lt:
    #         print("i.score = {}".format(lt[0]))


    print("--------------------------------")

    # s = [('name', 1), ('age', 1)]
    s = {'name': 1, 'age': 1}
    # s = {}
    lt = []
    while len(s) > 0:
        lt.insert(0, s.popitem())
    print(lt)
    # 查询全部2
    cur = coll.find()
    if len(lt) > 0:
        cur.sort(lt)
    for i in cur:
        print(i)

    print("--------------------------------")

    # 查询全部3 错误的版本
    # for i in coll.find().sort([{'_id': -1}]):
    #     print(i)

    # 插入一个文档
    # res0 = coll.insert({"name":"bbb", "msg":"1341", "score":[1,4,5,7,4,0]})
    # print(res0)

    # 插入多个文档
    # docList = [{"name":"bbb", "msg":"mmma1"},{"name":"bbb","msg":"mmma2"}]
    # res = coll.insert(docList)

    # 删除文档
    # res = coll.remove({"name": "bbb"})
    #
    # print(res)
